#include <QtGui>
#include "saveform.h"


SaveForm::SaveForm(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	fileLabel    = ui.suffixLabel;
	buttonGroup  = ui.buttonGroup;
	okButton     = ui.okButton;
	cancelButton = ui.cancelButton;
	fileEdit     = ui.fileEdit;


	QList<QAbstractButton *> buttons = buttonGroup->buttons();
	QPushButton *button = NULL;
	for(int index = 0; index < buttons.count(); ++index){
		button = qobject_cast<QPushButton *>(buttons.at(index));
		button->setFocusPolicy(Qt::NoFocus);

		connect(button, SIGNAL(clicked()), this, SLOT(editButtonsClicked()));
	}
	okButton->setFocusPolicy(Qt::NoFocus);
	cancelButton->setFocusPolicy(Qt::NoFocus);

	setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
	showMaximized();

	connect(okButton, SIGNAL(clicked()), this, SLOT(dialogShouldReturn()));
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(dialogShouldReturn()));
	
}



SaveForm::~SaveForm()
{
	delete fileLabel;
	delete okButton;
	delete cancelButton;
	delete fileEdit;

	QList<QAbstractButton *> buttons = buttonGroup->buttons();
	QPushButton *button = NULL;
	for(int index = 0; index < buttons.count(); ++index){
		button = qobject_cast<QPushButton *>(buttons.at(index));
		delete button;
	}

	delete buttonGroup;
}


QString SaveForm::getFilePath()
{
	return (fileEdit->text() + fileLabel->text());
}

void SaveForm::editButtonsClicked()
{
	QPushButton *button = qobject_cast<QPushButton *>(sender());
	QString button_text = button->text();

	int cursor_position = fileEdit->cursorPosition();
	QString edit_string = fileEdit->text();
	int edit_length = edit_string.length();
	QString left_string = edit_string.left(cursor_position);
	QString right_string = edit_string.right(edit_length - cursor_position);

	QString edited_string;
	if(button_text == tr("<=")){
		edited_string = left_string.left(cursor_position - 1) + right_string;
		fileEdit->setText(edited_string);
		fileEdit->setCursorPosition(cursor_position - 1);
	}else if(button_text == tr("CAPS")){
		QList<QAbstractButton *> buttons = buttonGroup->buttons();
		char button_char;
		for(int index = 0; index < buttons.count(); ++index){
			button = qobject_cast<QPushButton *>(buttons.at(index));
			button_text = button->text();
			if(button_text.length() == 1){
				button_char = button_text.at(0).toAscii();
				if((64 < button_char && button_char < 91) || (96 < button_char && button_char < 123)){
					button_char += ((button_char > 96) ? -32 : 32);
					button->setText(QString(QChar(button_char)));
				}
			}
		}

	}else{
		edited_string = left_string + button_text + right_string;
		fileEdit->setText(edited_string);
		fileEdit->setCursorPosition(cursor_position + 1);
	}
}


void SaveForm::dialogShouldReturn()
{
	QPushButton *button = qobject_cast<QPushButton *>(sender());
	(button == okButton) ? accept() : reject();
}
